import os
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QSystemTrayIcon, QMenu
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QMovie
import random
from chiikawa_desktop_pet.config.constant import *


class DesktopPet(QLabel):
    def __init__(self, parent=None):
        super(DesktopPet, self).__init__(parent)
        self.initUI()
        self.dragging = False

    def initUI(self):
        self.movie = QMovie(IMAGE['yeah.gif'])
        self.setMovie(self.movie)
        self.movie.start()
        self.setGeometry(100, 100, self.movie.frameRect().size(
        ).width(), self.movie.frameRect().size().height())
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

        # self.timer = QTimer()
        # self.timer.timeout.connect(self.randomMove)
        # self.timer.start(30 * 1000)

        self.timer = QTimer()
        self.timer.timeout.connect(self.changeActionTimely)
        self.timer.start(30 * 1000)

        self.trayIcon = QSystemTrayIcon(self)
        self.trayIcon.setIcon(QIcon(IMAGE['icon']))
        self.trayIcon.setToolTip('桌面宠物')
        self.trayIcon.show()

        menu = QMenu()
        exitAction = menu.addAction("退出")
        restartAction = menu.addAction("重启")
        exitAction.triggered.connect(self.close)
        restartAction.triggered.connect(self.restart)

        self.trayIcon.setContextMenu(menu)

        self.action_time = 1000

    def restart(self):
        # 关闭当前应用程序实例
        QApplication.instance().quit()
        # 使用系统调用重新启动应用程序
        os.execv(sys.executable, ["python", "app.py"])

    def randomMove(self):
        if not self.dragging:
            screenRect = QApplication.desktop().screenGeometry()
            x = random.randint(0, screenRect.width() - self.width())
            y = random.randint(0, screenRect.height() - self.height())
            self.move(x, y)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.offset = event.pos()
            self.dragging = True

    def mouseMoveEvent(self, event):
        if self.dragging:
            self.movie.stop()
            x = event.globalX()
            y = event.globalY()
            x_w = x - self.offset.x()
            y_w = y - self.offset.y()
            self.move(x_w, y_w)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.dragging = False
            self.inverseAnimation()
            
    def changeActionTimely(self):
        while True:
            action = random.choice(list(IMAGE.keys()))
            if ".gif" in action:
                break
        self.changeAction(action)

    def changeAction(self, action="yeah.gif"):
        # band when dragging
        if self.dragging:
            return
        # size
        pos = self.frameGeometry().topLeft() # (x, y)
        # action 
        self.movie.stop()
        self.movie = QMovie(IMAGE[action])
        self.setMovie(self.movie)
        self.movie.start()
        self.setGeometry(pos.x(), pos.y(),
                         self.movie.frameRect().size().width(),
                         self.movie.frameRect().size().height())
        # time 每个动作的时间不一样，因此放在这里设置很不错
        self.action_time = ACTION_TIME[action]
        QTimer.singleShot(self.action_time, self.inverseAnimation)

    def inverseAnimation(self):
        if self.movie.state() == QMovie.Running:
            self.movie.stop()
        else:
            self.movie.start()
            QTimer.singleShot(self.action_time, self.inverseAnimation)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    pet = DesktopPet()
    pet.show()
    sys.exit(app.exec_())
